package net.sf.odinms.exttools.doclet.pages;

import java.io.IOException;
import java.util.Arrays;
import com.sun.javadoc.PackageDoc;
import net.sf.odinms.exttools.doclet.AbstractPageWriter;
import net.sf.odinms.exttools.doclet.Doclet;

/**
 * Creates "overview-frame.html" which lists documented packages.
 */
public final class AllPackages extends AbstractPageWriter {
	
	/**
	 * Array of Packages to be documented.
	 */
	private PackageDoc[] packages;
	
	/**
	 * Generate content for upper-left frame, containing list of all packages.
	 * Only generated if Javadoc is given package parameters; doesn't appear
	 * when only individual files are specified.
	 */
	public static void generateAllPackages() {
		String filename = "overview-frame" + CONF.ext;
		try {
			new AllPackages(filename);
		}
		catch (IOException exc) {
			throw Doclet.exception(exc, filename);
		}
	}
	
	/**
	 * Initialize and create framed listing of all packages.
	 * 
	 * @param filename The desired name of the file (with extension).
	 * @throws IOException If {@link java.io.FileOutputStream} creation fails.
	 */
	private AllPackages(String filename) throws IOException {
		super(filename);
		pageType = PageType.ALL_PACKAGES;
		packages = CONF.packages;
		
		windowTitle = CONF.propertyText("OverviewTitle");
		String[] metakeywords = {windowTitle};
		if (CONF.doctitle.length() > 0) {
			metakeywords[0] += ", " + CONF.doctitle;
		}
		printXhtmlHeader(metakeywords, false, null);
		
		// Print "All Classes" link
		println(open("h3")
				+ linkToLabelHrefTarget(CONF.propertyText("AllPackages"),
						"overview-summary" + CONF.ext, "classFrame")
				+ close("h3"));
		
		println(openDivWithClass("packages"));
		
		// Print links to "{package}/package-frame.html" for all packages
		String href, label;
		if (packages.length > 0) {
			Arrays.sort(packages);
			for (PackageDoc pkg : packages) {
				if (pkg != null) {
					href =
							((pkg.name().length() > 0) ? pathToPackageFile(pkg,
									"") : "")
									+ "package-summary" + CONF.ext;
					label =
							(pkg.name().length() > 0)
									? pkg.name()
									: "&lt;unnamed package&gt;";
					println(linkToLabelHrefTarget(label, href, "classFrame")
							+ empty("br"));
				}
			}
		}
		println(close("div") + getComment("packages"));
		
		printXhtmlFooter();
		this.close();
	}
	
}
